package com.harmontronics.hanma.paas.paas.token;

import com.harmontronics.hanma.paas.paas.exception.TokenErrorException;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author ldb
 */
public interface TokenRenew {

    /**
     * 获取redis template
     * @return
     */
    StringRedisTemplate getRedisTemplate();

    /**
     * TOKEN
     * @return
     */
    TokenKit getTokenKit();
    /**
     * Token续签
     * @return
     */
    default UserInfo renew(){
        String token = getTokenKit().getTokenKey();
        //如果没有获取到TOKEN，直接返回false
        if (StringUtils.isEmpty(token)) {
           throw new TokenErrorException(HttpStatus.UNAUTHORIZED.value());
        }
        Long userId = getTokenKit().getId();

        String hashKey = getTokenKit().getTokenHashKey(userId);

        HashOperations<String, String, String> hashOperations = getRedisTemplate().opsForHash();
        Map<String, String> hashData = hashOperations.entries(hashKey);
        if (CollectionUtils.isEmpty(hashData)) {
            throw new TokenErrorException(HttpStatus.UNAUTHORIZED.value());
        }
        String expiredStr = hashData.get("KEY_" + token);
        if (expiredStr == null) {
            throw new TokenErrorException(HttpStatus.UNAUTHORIZED.value());
        }
        if ("0".equals(expiredStr)) {
            hashOperations.delete(hashKey, "KEY_" + token);
            throw new TokenErrorException(HttpStatus.LOCKED.value());

        }
        UserInfo userInfo = getTokenKit().map2UserInfo(hashData);
        Long rExpiredMilli = Long.parseLong(expiredStr);
        //续签
        if (rExpiredMilli <= System.currentTimeMillis()) {
            LocalDateTime expiredTime = LocalDateTime.now().plusHours(1);
            long expiredMilli = expiredTime.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
            hashOperations.put(hashKey, "KEY_" + token, String.valueOf(expiredMilli));
            getRedisTemplate().expire(hashKey, 2, TimeUnit.HOURS);
        }
        return userInfo;
    }

}
